package com.example.ktapplication.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.R
import com.example.ktapplication.bean.Media
import com.example.ktapplication.databinding.RvMusicItemLayoutBinding

class MusicListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val medias by lazy {
        mutableListOf<Media>()
    }

    var itemCallBack: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.rv_music_item_layout, parent, false)
        return MusicViewHolder(view)
    }

    override fun getItemCount(): Int {
        return medias.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addData(data: MutableList<Media>) {
        medias.clear()
        data.sortBy { it.title }
        medias.addAll(data)
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is MusicViewHolder) {
            val media = medias[position]
            holder.binding.llBody.setOnClickListener {
                itemCallBack?.onItemClick(media)
            }
            holder.binding.tvTitle.text = media.title
            holder.binding.tvUser.text = media.user
        }
    }

    inner class MusicViewHolder(item: View) : RecyclerView.ViewHolder(item) {
        val binding by lazy {
            RvMusicItemLayoutBinding.bind(item)
        }
    }

    interface OnItemClickListener {
        fun onItemClick(media: Media)
    }
}